﻿<?php

  //数据库操作文件


  //数据库链接函数
  function db_connect($db_name,$host='127.0.0.1',$db_user='root',$db_pwd='root',$charset='utf8'){
    $link=mysqli_connect($host,$db_user,$db_pwd,$db_name);
    if(!$link){
      echo'<script>alert("数据库链接失败");history.go(-1);</script>';
    }
    // mysqli_query(参数1，参数2)是专门用来执行sql语句的
    mysqli_query($link,'set names '.$charset);
    return $link;
  }


  //删除
  function db_delete($table,$where=array()){
    if(is_array($where)){
     $sty = implode(',',$where);
    }
    $sql = "delete from `$table` where `id`= $where ";
    mysqli_query($GLOBALS['link'],$sql);
    return mysqli_affected_rows($GLOBALS['link']);

  }


  //添加

  function db_add($table,$where=array()){
      $v = "'".implode("','",array_values($where))."'";
      $key= "`".implode("`,`",array_keys($where))."`";
    $sql = "insert into `$table`($key)values($v)";
    mysqli_query($GLOBALS['link'],$sql);
    return mysqli_affected_rows($GLOBALS['link']);

  }


     //修改
    function db_update($table,$where=array()){

     foreach ($where as $k => $v) {
        $con[]="`".$k."`='".$v."'";
     }
      /*    Array
      (
          [0] => `title`='11'
          [1] => `type`='1'
      )*/
      $con=implode(',',$con);
      $sql = "update `news`  set $con";
      mysqli_query($GLOBALS['link'],$sql);
      return mysqli_affected_rows($GLOBALS['link']);
    }


    //查找一条
      function db_selectOne($table,$where=1){
        if (empty($where)) {
          $where='where1';
        }else{
          $where='where'.$where;
         }
       $sql = "select $whole from `$table`$where";
       mysqli_query($GLOBALS['link'],$sql);
       return mysqli_affected_rows($GLOBALS['link']);

     }




    //查找多条
     //  function db_select($table,$where,$whole='*'){
     //      $sty = '';
     //      $i = 0 ;
     //      foreach ($where as $k => $v) {
     //        if ($i = count($where+1)) {
     //          $sty .="`$k`= `$v`";
     //        }else{
     //          $sty .="`$k`= `$v` and";
     //         }
     //        i++;
     //      }
     //   $sql = "select $whole from `$table` where $where limit 1 ";
     //   mysqli_query($GLOBALS['link'],$sql);
     //   return mysqli_affected_rows($GLOBALS['link']);

     // }
  ?>